package com.lsh.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.lsh.service.ProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/3/17 4:23 下午
 * @desc ：
 */
@Service
public class ProviderServiceImpl implements ProviderService {

    @Autowired
    RedisTemplate redisTemplate;



    /**
     * 指定序列化方式
     */
    @PostConstruct
    public void init() {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        redisTemplate.setHashValueSerializer(redisSerializer);
    }


    @Override
    public String minusAppleNum() {
        String resp = "";
        if (Math.random()>0.5){
            resp = "9999";
            String appleStock = (String) redisTemplate.opsForValue().get("AppleStock");
            System.out.println("==============================");
            System.out.println("苹果库存扣减失败,库存还剩 "+appleStock+" 个");
            throw new RuntimeException("Exception");
        }else{
            redisTemplate.opsForValue().decrement("AppleStock",1L);
            String appleStock = (String) redisTemplate.opsForValue().get("AppleStock");
            System.out.println("==============================");
            System.out.println("苹果库存扣减成功，库存还剩 "+appleStock+" 个");

            resp ="0000";
        }

        return resp;

    }
}
